package tk.mynoteapp.dev.other.eliminateifelse.right.responsibility;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 责任链模式
 * 责任链模式：将请求的处理对象像一条长链一般组合起来，形成一条对象链。请求并不知道具体执行请求的对象是哪一个，这样就实现了请求与处理对象之间的解耦。
 * 关键是每个PayHandler的子类，都定义了下一个需要执行的PayHandler子类，构成一个链式调用，通过PayHandlerChain把这种链式结构组装起来
 */
@Service
public class PayHandlerChain implements ApplicationContextAware, InitializingBean {
    private ApplicationContext applicationContext;
    private PayHandler header; // 链条头部（第一个处理者）

    /**
     * 处理方法
     * @param code
     */
    public void handlePay(String code) {
        header.pay(code);
    }

    /**
     * 初始化链条
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, PayHandler> beansOfType = applicationContext.getBeansOfType(PayHandler.class);
        if (beansOfType == null || beansOfType.isEmpty()) {
            return;
        }
        List<PayHandler> handlers = beansOfType.values().stream().collect(Collectors.toList());
        for (int i = 0; i < handlers.size(); i++) {
            PayHandler handler = handlers.get(i);
            if (i != handlers.size() - 1) {
                handler.setNext(handlers.get(i + 1));
            }
        }
        header = handlers.get(0);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
